package com.cosina.game.crystallight.engine;

import com.cosina.game.crystallight.MediaPlayerAdapter;
import com.cosina.game.crystallight.dao.ProfileDAOFacade;
import com.cosina.game.crystallight.model.battle.BattleField;
import com.cosina.game.crystallight.model.battle.BattleFieldFactory;
import com.cosina.game.crystallight.model.battle.BattleFieldProxy;
import com.cosina.game.crystallight.model.battle.BattleFieldProxyManager;
import com.cosina.game.crystallight.model.crystal.Desk;
import com.cosina.game.crystallight.model.profile.ProfileManager;

public class BattleEngine {

	public static BattleField field;
	public static Architect architect;
	public static ManaFlask manaFlask;
	public static Sheild sheild;
	public static AbilityManager abilityManager;
	public static EvilNest wavePanelManager;
	public static BattleFieldProxy tollGate;
	public static EnemyManager enemyManager;
	public static TouchHandler touchHandler;
	public static SpeedManager speedManager;
	public static PsManager psManager;
	public static Desk desk;
	public static Status status;
	public static BattleStatistics statistics;
	public static FlyingManager flyingManager;
	public static void start(int tollGateId) {
		statistics = new BattleStatistics();
		field = BattleFieldFactory.get(tollGateId);
		manaFlask = new ManaFlask();
		architect = new Architect();
		sheild = new Sheild();
		abilityManager = new AbilityManager();
		tollGate = BattleFieldProxyManager.get(tollGateId);
		enemyManager = new EnemyManager();
		wavePanelManager = new EvilNest(enemyManager, tollGate);
		touchHandler = new TouchHandler();
		speedManager = new SpeedManager();
		desk = new Desk();
		psManager = new PsManager();
		flyingManager = new FlyingManager();
		status = Status.running;
	}

	public static enum Status {
		running, victory, defeat;
	}

	public static void withTimeGoRoot() {
		if (architect.isBuildModel()) {
			return;
		}
		if (status == Status.running) {
			wavePanelManager.withTimeGo();
			enemyManager.withTimeGo();
			architect.withTimeGo();
			psManager.withTimeGo();
			statistics.withTimeGo();
			flyingManager.withTimeGo();
			if (isDefeat()) {
				MediaPlayerAdapter.defeat();
				status = Status.defeat;
			} else 
			if (isVictory()) {
				MediaPlayerAdapter.victory();
				status = Status.victory;
				
				ProfileManager.getCurrentProfile().tollGateManager.newOvered(field.getId());
				ProfileManager.getCurrentProfile().stats.proposalStatistics(statistics);
				ProfileDAOFacade.saveCurrentProfile();
			}
		}
		if(status == Status.victory){
			flyingManager.withTimeGo();
		}
	}
	
	private static boolean isDefeat(){
		return sheild.isBroken();
	}
	private static boolean isVictory(){
		return enemyManager.noEnemy()
		&& false == wavePanelManager.hasNextLevel();
	}
}
